<template>
  <label :class="['yd-radio',modelValue==value||activeValue==value?'is-checked':'']">
    <span class="radio-icon">
      <span class="radio-inner"></span>
      <input class="radio-original" type="radio" :name="name" :value="value" v-model="myModel" />
    </span>
    <span class="radio-label">
      <slot>{{label}}</slot>
    </span>
  </label>
</template>

<script>
import { ref, computed, getCurrentInstance, watch, inject } from "vue";
export default {
  name: "yd-radio",
  props: {
    label: {
      type: String,
      default: ""
    },
    value: null,
    name: null,
    modelValue: null
  },
  setup(props, ctx) {
    const group = getCurrentInstance().parent;
    let activeValue = ref();

    const isInGroup = computed(() => {
      return Boolean(group.vnode.type.name === "yd-radio-group");
    });
    if (isInGroup.value) {
      activeValue.value = inject("gValue");
    }
    const myModel = computed({
      get() {
        return isInGroup.value ? group.ctx.modelValue : props.modelValue;
      },
      set() {
        return isInGroup.value
          ? group.emit("update:modelValue", props.value)
          : ctx.emit("update:modelValue", props.value);
      }
    });
    watch(
      () => group.ctx.modelValue,
      () => {
        activeValue.value = group.ctx.modelValue;
      }
    );
    return {
      myModel,
      activeValue
    };
  }
};
</script>

<style lang="scss" scoped>
.yd-radio {
  display: inline-block;
  position: relative;
  margin-right: 30px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  // 根据字号大小设置行距
  line-height: 1;
  outline: none;
  white-space: nowrap;
  cursor: pointer;
  // 禁止文本选择
  -moz-user-select: none;
  -webkit-user-select: none;
  .radio-icon {
    position: relative;
    display: inline-block;
    line-height: 1;
    vertical-align: middle;
    outline: none;
    white-space: nowrap;
    cursor: pointer;
    .radio-inner {
      position: relative;
      display: inline-block;
      width: 14px;
      height: 14px;
      box-sizing: border-box;
      border: 1px solid #dcdfe6;
      border-radius: 50%;
      cursor: pointer;
      &::after {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        width: 5px;
        height: 5px;
        border-radius: 50%;
        background-color: #409eff;
        // scale显示与隐藏
        transform: translate(-50%, -50%) scale(0);
        transition: transform 0.15s ease-in;
      }
    }
    .radio-original {
      opacity: 0;
      outline: none;
      position: absolute;
      cursor: pointer;
    }
  }
  .radio-label {
    font-size: 14px;
    padding-left: 10px;
  }
  &.is-checked {
    .radio-icon {
      .radio-inner {
        border-color: #409eff;
        &::after {
          transform: translate(-50%, -50%) scale(1);
        }
      }
    }
    .radio-label {
      color: #409eff;
    }
  }
}
</style>